package app

import (
	"common/logs"
	"context"
	"core/remote/node"
	"game/route"
	"os"
	"os/signal"
	"syscall"
)

func Run(ctx context.Context, serverId string) error {
	// 1. 创建连接并启动
	n := node.Default()
	go func() {
		// 注册 Handler
		n.RegisterHandler(route.Handlers())
		if err := n.Run(serverId); err != nil {
			logs.Fatal("服务启动异常：%v", err)
		}
	}()
	stop := func() {
		n.Close()
		logs.Info("stop app finish.")
	}
	// 2. 优雅启停
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGHUP)
	select {
	case <-ctx.Done():
		stop()
	case s := <-c:
		switch s {
		case syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT:
			stop()
			logs.Warn("connector app quit.")
		case syscall.SIGHUP:
			stop()
			logs.Warn("hang up!! connector app quit.")
		}
	}
	return nil
}
